﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Report_Unity.Basic
{
    public static class CodeStatusExtendsion
    {
        public static ResultInfo GetStatus(this Enum e, string info = "")
        {
            ResultInfo res = new ResultInfo();
            Type type = e.GetType();
            FieldInfo feild = type.GetField(e.ToString());
            res.code = (int)feild.GetValue(e);
            if (feild.IsDefined(typeof(RemarkAttribute)))
            {
                RemarkAttribute attribute = feild.GetCustomAttribute(typeof(RemarkAttribute)) as RemarkAttribute;
                string mark = attribute.GetRemark();
                if (string.IsNullOrEmpty(info))
                    res.msg = mark;
                else
                    res.msg = string.Format(mark, info);
            }
            return res;
        }

        public static IDictionary<string, string> GetBasicInfoPropInfo<T>(this T t) where T : class, new()
        {
            Type type = t.GetType();
            PropertyInfo[] props = type.GetProperties();
            IDictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var prop in props)
            {
                if (prop.IsDefined(typeof(RemarkAttribute)))
                {
                    string fieldName = prop.Name;
                    RemarkAttribute attribute = prop.GetCustomAttribute(typeof(RemarkAttribute)) as RemarkAttribute;
                    string remark = attribute.GetRemark();
                    dic.Add(fieldName, remark);
                }
            }

            return dic;
        }


        /// <summary>
        /// 获取枚举上的Remark类描述
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetEnumDesc(this Enum e)
        {
            string res = string.Empty;
            Type type = e.GetType();
            FieldInfo feild = type.GetField(e.ToString());
            if (feild.IsDefined(typeof(RemarkAttribute)))
            {
                RemarkAttribute attribute = feild.GetCustomAttribute(typeof(RemarkAttribute)) as RemarkAttribute;
                res = attribute.GetRemark();
            }
            return res;
        }

        /// <summary>
        /// 清除换行和空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DumpSpaceAndLinebreak(this string str)
        {
            str = str.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
            return str;
        }
    }
}
